<template>
  <div>
    <!-- 搜索筛选 -->
    <el-form :inline="true" class="mg-top-20">
      <el-form-item>
        <el-button
          size="small"
          type="primary"
          icon="el-icon-plus"
          @click="handleEdit()"
          >添加</el-button
        >
      </el-form-item>
    </el-form>
    <!--列表-->
    <el-table
      size="small"
      :data="tasks"
      highlight-current-row
      v-loading="$store.state.loading"
      border
      element-loading-text="拼命加载中"
      style="width: 100%"
    >
      <el-table-column align="center" type="selection" width="60">
      </el-table-column>
      <el-table-column sortable prop="name" label="任务名称" width="200">
      </el-table-column>
      <el-table-column
        sortable
        prop="type"
        :formatter="typeFormat"
        label="类型"
        width="100"
      >
      </el-table-column>
      <el-table-column sortable prop="desc" label="描述" width="150">
      </el-table-column>
      <el-table-column sortable prop="createAt" label="创建时间" width="150">
        <template slot-scope="scope">
          <div>{{ scope.row.createAt | timestampToTime }}</div>
        </template>
      </el-table-column>
      <el-table-column
        sortable
        prop="state"
        :formatter="stateFormat"
        label="状态"
        width="80"
      >
      </el-table-column>
      <el-table-column
        sortable
        :formatter="stateFormat"
        label="执行日志"
        width="100"
      >
        <template slot-scope="scope">
          <el-button plain @click="handleShowLog(scope.row)" size="mini"
            >查看</el-button
          >
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" min-width="200">
        <template slot-scope="scope">
          <el-button size="mini" @click="handleEdit(scope.$index, scope.row)"
            >编辑</el-button
          >
          <el-button
            v-if="scope.row.state == 'running'"
            size="mini"
            type="danger"
            @click="handlePause(scope.$index, scope.row)"
            plain
            >停止</el-button
          >
          <el-button
            v-if="scope.row.state == 'stopped'"
            size="mini"
            type="success"
            @click="handleResume(scope.$index, scope.row)"
            plain
            >启动</el-button
          >
          <el-button
            v-if="scope.row.state == 'finished'"
            size="mini"
            type="success"
            @click="handleRenew(scope.$index, scope.row)"
            plain
            >重新开启</el-button
          >
          <el-popconfirm
            v-if="scope.row.state != 'running'"
            title="确认要删除？"
            @confirm="handleDelete(scope.$index, scope.row)"
            class="mg-left-10"
          >
            <el-button slot="reference" size="mini" type="danger" plain
              >删除</el-button
            >
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页组件 -->
    <Pagination
      :data="query"
      @onPageChange="getdata"
      @onSizeChange="getdata"
    ></Pagination>

    <!-- 编辑界面 -->
    <el-dialog
      :title="title"
      :visible.sync="editFormVisible"
      width="60%"
      @click="closeDialog"
    >
      <el-form
        label-width="120px"
        :rules="rules"
        :model="editForm"
        ref="editForm"
      >
        <el-form-item label="任务名称" prop="name">
          <el-input
            size="small"
            v-model="editForm.name"
            auto-complete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="任务类型" prop="type">
          <el-radio-group v-model="editForm.type">
            <el-radio :label="'timer'">定时执行</el-radio>
            <el-radio :label="'delay'">延时执行</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item
          v-if="editForm.type == 'timer'"
          prop="expression"
          label="cron表达式"
        >
          <el-input
            size="small"
            v-model="editForm.expression"
            auto-complete="off"
          >
            <template slot="append">
              <a href="http://cron.ciding.cc/" target="_blank"
                >cron表达式生成器</a
              >
            </template>
          </el-input>
        </el-form-item>
        <el-form-item
          v-if="editForm.type == 'delay'"
          prop="seconds"
          label="延时时间(秒)"
        >
          <el-input
            size="small"
            v-model="editForm.seconds"
            auto-complete="off"
            @input="secondsInput"
          >
            <template slot="append">{{ editForm.secondsDesc }}</template>
          </el-input>
        </el-form-item>
        <el-form-item label="执行动作" prop="actions">
          <el-card
            class="box-card"
            v-for="action in editForm.actions"
            :value="action"
            :key="action.name"
          >
            <el-row>
              <el-col :span="22"
                ><Action :data="action" actions="device"></Action
              ></el-col>
              <el-col :span="2"
                ><el-button size="small" type="error" @click="delAction(action)"
                  >删除</el-button
                ></el-col
              >
            </el-row>
          </el-card>
          <el-button size="small" @click="addAction()">新增</el-button>
        </el-form-item>
        <el-form-item label="任务描述" prop="desc">
          <el-input
            size="small"
            v-model="editForm.desc"
            auto-complete="off"
            type="textarea"
            :rows="2"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="closeDialog">取消</el-button>
        <el-button
          :disabled="editForm.state == 'running'"
          size="small"
          type="primary"
          :loading="$store.state.loading"
          class="title"
          @click="submitEditForm('editForm')"
          >保存</el-button
        >
      </div>
    </el-dialog>

    <el-dialog title="任务执行日志" :visible.sync="showLogVisible" width="60%">
      <TaskLogs :taskId="taskId"></TaskLogs>
    </el-dialog>
  </div>
</template>

<script>
import { uuid } from "@/utils/util.js";
import Pagination from "@/components/Pagination";
import Action from "./Action.vue";
import TaskLogs from "./TaskLogs.vue";
import {
  TaskList,
  TaskSave,
  TaskPause,
  TaskResume,
  TaskRenew,
  TaskDelete,
} from "@/api/ruleApi.js";
export default {
  data() {
    var validateExpression = (rule, value, callback) => {
      if (this.editForm.type == "timer" && value === "") {
        callback(new Error("请输入cron表达式"));
      } else {
        callback();
      }
    };
    var validateSeconds = (rule, value, callback) => {
      if (this.editForm.type == "delay" && value === "") {
        callback(new Error("请输入延时时间"));
      } else {
        callback();
      }
    };
    var validateAction = (rule, value, callback) => {
      if (this.editForm.actions.length == 0) {
        callback(new Error("请设置输出"));
      } else {
        callback();
      }
    };
    return {
      loading: false,
      title: "",
      tasks: [],
      query: {
        page: 1,
        size: 10,
        total: 0,
      },
      editForm: {
        name: "",
        state: "",
        type: "timer",
        expression: "",
        seconds: "",
        actions: [],
        desc: "",
      },
      rules: {
        name: [{ required: true, message: "请输入任务名称", trigger: "blur" }],
        expression: [{ validator: validateExpression, trigger: "blur" }],
        seconds: [{ validator: validateSeconds, trigger: "blur" }],
        actions: [{ validator: validateAction, trigger: "blur" }],
      },
      editFormVisible: false,
      showLogVisible: false,
      taskId: "",
    };
  },
  components: {
    Pagination,
    Action,
    TaskLogs,
  },
  created() {
    this.getdata();
  },
  methods: {
    getdata(params) {
      TaskList(params).then((rst) => {
        this.tasks = rst;
      });
    },
    typeFormat(row, column, value) {
      return value == "timer" ? "定时任务" : value == "delay" ? "延时任务" : "";
    },
    stateFormat(row, column, value) {
      switch (value) {
        case "stopped":
          return "已停止";

        case "running":
          return "运行中";

        case "invalid":
          return "不可用";

        case "finished":
          return "已完成";
      }
    },
    handleEdit(index, row) {
      this.editFormVisible = true;
      if (row != undefined && row != "undefined") {
        this.title = "编辑定时任务";
        this.editForm.id = row.id;
        this.editForm.state = row.state;
        this.editForm.name = row.name;
        this.editForm.type = row.type;
        this.editForm.expression = row.expression;
        this.editForm.desc = row.desc;
        this.editForm.actions = [];
        row.actions.forEach((a) => {
          this.editForm.actions.push(JSON.parse(a.config));
        });

        if (row.type == "delay") {
          this.editForm.seconds = row.expression;
          this.secondsInput(this.editForm.seconds);
        }
      } else {
        this.title = "添加定时任务";
        this.editForm.state = "";
        this.editForm.id = "";
        this.editForm.name = "";
        this.editForm.type = "timer";
        this.editForm.expression = "";
        this.editForm.seconds = "";
        this.editForm.desc = "";
        this.editForm.actions = [];
      }
    },
    handlePause(index, row) {
      TaskPause(row.id).then(() => {
        this.getdata();
      });
    },
    handleResume(index, row) {
      TaskResume(row.id).then(() => {
        this.getdata();
      });
    },
    handleRenew(index, row) {
      TaskRenew(row.id).then(() => {
        this.getdata();
      });
    },
    handleDelete(index, row) {
      TaskDelete(row.id).then(() => {
        this.getdata();
      });
    },
    secondsInput(val) {
      if (val < 60) {
        val = val + "秒";
      } else if (val < 3600) {
        val = parseInt(val / 60) + "分" + (val % 60) + "秒";
      } else {
        val =
          parseInt(val / 3600) +
          "时" +
          parseInt((val % 3600) / 60) +
          "分" +
          (val % 60) +
          "秒";
      }
      this.editForm.secondsDesc = val;
    },
    addAction() {
      this.editForm.actions.push({
        id: uuid(),
        type: "device",
        services: [],
      });
    },
    delAction(action) {
      let idx = this.editForm.actions.findIndex((o) => o.id == action.id);
      this.editForm.actions.splice(idx, 1);
    },
    submitEditForm(from) {
      console.log(this.editForm);
      this.$refs[from].validate((valid) => {
        if (valid) {
          if (this.editForm.type == "delay") {
            this.editForm.expression = this.editForm.seconds;
          }
          let task = JSON.parse(JSON.stringify(this.editForm));
          task.actions.forEach((t) => {
            t.config = JSON.stringify(t);
          });
          TaskSave(task).then(() => {
            this.editFormVisible = false;
            this.$message({
              type: "success",
              message: "保存成功！",
            });
            this.getdata();
          });
        }
      });
    },
    closeDialog() {
      this.editFormVisible = false;
    },
    handleShowLog(row) {
      this.taskId = row.id;
      this.showLogVisible = true;
    },
  },
};
</script>
